package com.dz.util;

import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//验证码过期容器
public class ExpiryMap {
    // 存储数据的Map容器
    private static java.util.Map<String, Object> map = new java.util.HashMap<String, Object>();
    // 存储过期时间的Map容器
    private Map<String, Long> expiryMap = new java.util.HashMap<String, Long>();

    // 定时任务线程池
    private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    // 检查过期时间间隔
    private long expiryTime = 1000 * 6;

    public ExpiryMap() {
        // 启动定时任务，每隔expiryTime毫秒执行一次clearExpired方法
        service.scheduleAtFixedRate(this::clearExpired, expiryTime, expiryTime, TimeUnit.MILLISECONDS);
    }

    public ExpiryMap(long expiryTime) {
        this.expiryTime = expiryTime;
        service.scheduleAtFixedRate(this::clearExpired, expiryTime, expiryTime, TimeUnit.MILLISECONDS);
    }

    public void put(String key, Object value){
        map.put(key, value);
        expiryMap.put(key, System.currentTimeMillis() + expiryTime);
    }

    public void put(String key, Object value, long expiryTime){
        map.put(key, value);
        expiryMap.put(key, System.currentTimeMillis() + expiryTime);
    }

    public Object get(String key){
        Long expiryTime = expiryMap.get(key);
        if (expiryTime == null || expiryTime < System.currentTimeMillis()) {
            map.remove(key);
            expiryMap.remove(key);
        }
        return map.get(key);
    }

    public void remove(String key){
        map.remove(key);
        expiryMap.remove(key);
    }

    public boolean containsKey(String key){
        Long expiryTime = expiryMap.get(key);
        if (expiryTime == null || expiryTime < System.currentTimeMillis()) {
            map.remove(key);
            expiryMap.remove(key);
        }
        return map.containsKey(key);
    }

    // 清除过期数据
    public void clearExpired() {
        for (String key : expiryMap.keySet()) {
            // 判断是否过期
            if (System.currentTimeMillis() > expiryMap.get(key)) {
                map.remove(key);
                expiryMap.remove(key);
            }
        }
    }
}
